﻿using D.UtilCore.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace D.UtilCore.Filters
{
    /// <summary>
    /// 异步响应结果补充
    /// 执行顺序：1. Action执行完后> OnResultExecuting> 渲染UI视图> OnResultExecuted
    /// 使用场景：Json格式统一处理返回参数
    /// </summary>
    public class ExtResultAsyncFilterAttribute : Attribute, IAsyncResultFilter
    {

        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // 渲染结果之前
            if (context.Result is JsonResult)
            {
                var result = (JsonResult)context.Result;
                context.Result = new JsonResult(new ApiResult<object>()
                {
                    Data = result.Value
                });
            }

            await next.Invoke();
        }
    }
}
